package top.birdhk.TestAPI.processfunction;

import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import top.birdhk.TestAPI.beans.SensorReading;

/**
 * 侧输出流
 */
public class ProcessTest_SideOutputCase {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        env.setParallelism(1);

//        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 7777);


        DataStream<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 定义一个outputTag，用来表示低温流
        // 加{}使用匿名内部类的方式
        OutputTag<SensorReading> outputTag = new OutputTag<SensorReading>("low-temp"){};

        // 测试keyedprocessFunction，自定义侧输出流
        SingleOutputStreamOperator<SensorReading> highTemp = inputStream
                .process(new ProcessFunction<SensorReading, SensorReading>() {
                    @Override
                    public void processElement(SensorReading sensorReading, Context context, Collector<SensorReading> collector) throws Exception {
                        // 判断温度，大于30度，高温流输出到主流，低温流输出到测输出流
                        if (sensorReading.getTemperature() > 30){
                            collector.collect(sensorReading);
                        }else{
                            // 输出到低温流
                            context.output(outputTag,sensorReading);
                        }
                    }
                });


        highTemp.print("high-temp");
        highTemp.getSideOutput(outputTag).print("low-temp");

        env.execute();

    }




}
